
import 'package:bookshelf/entity/book_entity.dart';
import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/page/rank_detail_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../http/api_url.dart';
import '../main.dart';
import '../widget/app_bar.dart';
import '../util/timer_manager.dart';

class Rank extends StatefulWidget {
  const Rank({Key? key}) : super(key: key);

  @override
  State<Rank> createState() => _RankState();
}

class _RankState extends State<Rank> {

  final RxList<BookEntity> _list = RxList();

  String type = 'read';


  @override
  initState() {
    super.initState();

    type = Get.arguments;

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        timer.cancel();
        Get.back();
      });
    });

    initData();
  }

  initData() {

    if(type == 'read'){
      hot().then((value){
        if(value != null){
          _list.addAll(value);
        }
      });
    }else{
      recommend().then((value){
        if(value != null){
          _list.addAll(value);

        }
      });
    }
  }

  _title(){
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w),
      child: Stack(
        alignment: AlignmentDirectional.centerStart,
        children: [
          InkWell(
            onTap: (){
              timer.cancel();
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:50.w,fit: BoxFit.fitWidth,)
          ),
          Align(child: Image.asset("assets/images/${type=='read'?'read_title':'recommend_title'}.png",width:100.w,fit: BoxFit.fitWidth,),),
          Positioned(right:0,child: Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),)))

        ],
      )
    );
  }



  _itemBuilder(index){
    var item = _list[index];
    RxBool showAnimation = false.obs;
    RxInt recommendCount = (item.score??0).obs;
    return InkWell(
      onTap: (){
        Get.to(()=> const RankDetail(),arguments: (item.book_id, item.title,null));
      },
      child: Container(
          margin: EdgeInsets.only(top: 5.r,left: 8.r,right: 8.r),
          padding: EdgeInsets.only(top: 5.r,bottom:5.r,left: 8.r,right: 8.r),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(4.r)),
          ),
          child: Stack(
            children: [
              Positioned(child: Image.network('${item.cover}',width: 66.w,height:89.h,fit: BoxFit.fill,
                errorBuilder: ( BuildContext context, Object error, StackTrace? stackTrace,){
                  return  Image.asset('assets/images/default.png',width: 66.w,height:89.h,fit: BoxFit.fill);
                },),),
              Positioned(child: Image.asset("assets/images/top${index+1}_bg.png",width: 67.w,height:90.h,fit: BoxFit.fill,),),
              Positioned(left:80.w,top:6.h,right:50.w,
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Text('《${item.title}》',maxLines:1,style: TextStyle(color: Colors.black,fontSize: 10.sp,fontWeight: FontWeight.bold),),
                  )
              ),
              Positioned(left:80.w,top:22.h,child: Text('${item.author}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              Positioned(left:80.w,top:40.h,child: Container(
                width: 24.w,
                height: 12.h,
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.fill,
                    image: AssetImage(
                      "assets/images/rank_left.png",
                    ),
                  ),
                ),
                child: Text('No.${index+1}',style: TextStyle(color: const Color.fromRGBO(208, 162, 97, 1),fontSize: 6.sp),),
              )),
              Positioned(left:104.w,top:40.h,child: Container(
                width: 38.w,
                height: 12.h,
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.fill,
                    image: AssetImage(
                      "assets/images/rank_right.png",
                    ),
                  ),
                ),
                child: Text(type=='read'?'借阅榜热门':'推荐榜热门',style: TextStyle(color: Colors.white, fontSize: 6.sp),),
              )),
              Positioned(left:150.w,top:40.h,child: InkWell(
                onTap: (){
                  resort.addById(item.book_id);
                  recommendCount.value = recommendCount.value +1;
                  item.score = recommendCount.value;
                  if(!showAnimation.value){
                    showAnimation.value = true;
                    Future.delayed(const Duration(milliseconds: 300),(){
                      showAnimation.value = false;
                    });
                  }
                },
                child: Image.asset("assets/images/like_click.png",width: 40.w,fit: BoxFit.fitWidth)
              )),
              Positioned(left:160.w,top:8.h,child: Obx(() => InkWell(
                onTap: (){
                  resort.addById(item.book_id);
                  recommendCount.value = recommendCount.value +1;
                  item.score = recommendCount.value;
                  if(!showAnimation.value){
                    showAnimation.value = true;
                    Future.delayed(const Duration(milliseconds: 300),(){
                      showAnimation.value = false;
                    });
                  }
                },
                child: Visibility(visible:showAnimation.value,child: Image.asset("assets/images/star.gif",width: 40.w,fit: BoxFit.fitWidth)))),
              ),
              Positioned(left:185.w,top:35.h,child: Container(
                width: 10.w,
                height: 10.w,
                alignment: Alignment.center,
                decoration:  BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(44.r)),
                    color: const Color.fromRGBO(255, 0, 0, 1)
                ),
                child: Obx(() => Text('${recommendCount.value>999?'999+':recommendCount.value}',style: TextStyle(color: Colors.white, fontSize: 4.sp),)),
              )),
              Positioned(left:80.w,top:55.h,child: Text('出版社：${item.publisher}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              // Positioned(left:80.w,top:55.h,child: Text('位置：二楼A区 第一列 第一层 A面',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              Positioned(left:80.w,top:70.h,child: Text('索书号：${item.search_no}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              if(index == 0)...[
                Positioned(right:0,top:10.h,child: Image.asset("assets/images/top1.png",width: 67.w,fit: BoxFit.fitWidth,),),
              ],
              if(index == 1)...[
                Positioned(right:0,top:10.h,child: Image.asset("assets/images/top2.png",width: 67.w,fit: BoxFit.fitWidth,),),
              ],
              if(index == 2)...[
                Positioned(right:0,top:10.h,child: Image.asset("assets/images/top3.png",width: 67.w,fit: BoxFit.fitWidth,),),
              ]

            ],
          )
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/rank_bg.png",
            ),
          ),
        ),
        child: Column(
          children: [
            appBar(bg: 'rank_top_bg'),
            _title(),
           Obx(() => Expanded(child: ListView.builder(
             itemBuilder: (context, index) {
               return _itemBuilder(index);
             },
             itemCount: _list.length,
           ),))
          ],
        ),
      ),
    );
  }
}

